//
//  tab_Search.m
//  VivaModa
//
//  Created by Owly MacBook on 01.02.13.
//  Copyright (c) 2013 private_busines. All rights reserved.
//

#import "tab_Search.h"

@interface tab_Search (){
    NSMutableArray *products;
    sortOrnament current_sort;
    increase current_increase;
}

@end

@implementation tab_Search

@synthesize infoData;
@synthesize button_sort_down;
@synthesize button_sort_up;
@synthesize detail_product;
@synthesize button_sort_avaliable;
@synthesize button_sort_name;
@synthesize button_sort_price;



int lastIndexsSortSearch[] = {-1,-1};/// 1 - up/down  2 - sortName

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}



-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
}




#pragma mark sortButtons Action

-(IBAction)sortButtonPress:(id)sender{
    if ([sender tag]==1) {
        current_increase = increase_up;
        if (current_sort == sort_name) {
            [UserDefaults setObject:@"1" forKey:@"search_last_Increase_name_up"];
        }else{
            [UserDefaults setObject:@"1" forKey:@"search_last_Increase_price_up"];
        }
    }else{
        current_increase = increase_down;
        if (current_sort == sort_name) {
            [UserDefaults setObject:@"0" forKey:@"search_last_Increase_name_up"];
        }else{
            [UserDefaults setObject:@"0" forKey:@"search_last_Increase_price_up"];
        }
    }
    [self setStateSortButtons];
    [self sortDataTableView];
}


-(void)setStateSortButtons{
    if (current_sort == sort_availability) {
        [self setHiddenSortBtn:YES];
    }else{
        [self setHiddenSortBtn:NO];
        switch (current_increase) {
            case increase_up:{
                NSLog(@"inrcease up");
                [self.button_sort_up setBackgroundImage:[UIImage imageNamed:@"button_arrow_up"] forState:UIControlStateNormal];
                [self.button_sort_down setBackgroundImage:[UIImage imageNamed:@"button_arrow_disabled"] forState:UIControlStateNormal];
                break;}
            case increase_down:{
                NSLog(@"increase down");
                [self.button_sort_up setBackgroundImage:[UIImage imageNamed:@"button_arrow_up_disabled"] forState:UIControlStateNormal];
                [self.button_sort_down setBackgroundImage:[UIImage imageNamed:@"button_arrow"] forState:UIControlStateNormal];
                break;}
            default:
                break;
        }
        
    }
}


-(void)setHiddenSortBtn:(BOOL)hide{
    self.button_sort_down.hidden = hide;
    self.button_sort_up.hidden = hide;
}


-(void)getCurrentSortData{
    
    if ([[UserDefaults objectForKey:@"last_sort_index"] integerValue]==51) {
        current_sort = sort_name;
    }else{
        if ([[UserDefaults objectForKey:@"last_sort_index"] integerValue]==53) {
            current_sort = sort_price;
        }else{
            if ([[UserDefaults objectForKey:@"last_sort_index"] integerValue]==52) {
                current_sort = sort_availability;
            }else{
                current_sort = sort_name; //default
            }
        }
        
    }
    
    
    
    switch (current_sort) {
        case sort_name:{
            ////////////////// Name
            if ([[UserDefaults objectForKey:@"last_Increase_name_up"] length]>0 & [[UserDefaults objectForKey:@"last_Increase_name_up"] length]<2){
                if ([[UserDefaults objectForKey:@"last_Increase_name_up"] integerValue]==1) {
                    current_increase = increase_up;
                }else{
                    current_increase = increase_down;
                    [UserDefaults setObject:@"0" forKey:@"last_Increase_name_up"];
                }
            }else{
                //// defauly value
                current_increase = increase_up;
                [UserDefaults setObject:@"1" forKey:@"last_Increase_name_up"];
            }
            
            break;}
        case sort_availability:{
            
            break;}
        case sort_price:{
            ////////////////// Price
            if ([[UserDefaults objectForKey:@"last_Increase_price_up"] length]>0 & [[UserDefaults objectForKey:@"last_Increase_price_up"] length]<2) {
                if ([[UserDefaults objectForKey:@"last_Increase_price_up"] integerValue]==1) {
                    current_increase = increase_up;
                }else{
                    current_increase = increase_down;
                    [UserDefaults setObject:@"0" forKey:@"last_Increase_price_up"];
                }
            }else{
                ////// default value
                current_increase = increase_up;
                [UserDefaults setObject:@"1" forKey:@"last_Increase_price_up"];
            }
            
            break;}
        default:
            break;
    }
    
    
}

-(void)sortDataTableView{
    if (lastIndexsSortSearch[0]==current_increase) {
        if (lastIndexsSortSearch[1]==current_sort) {
            [self.searchDisplayController.searchResultsTableView reloadData];
            return;
        }
    }
    
    lastIndexsSortSearch[0] = current_increase;
    lastIndexsSortSearch[1] = current_sort;
    NSLog(@"GO SORT");
    
    
    bool ascending;
    if (current_increase == increase_up) {
        ascending = YES;
    }else{
        ascending = NO;
    }
    
    NSSortDescriptor * sort;
    NSArray *tempArr;
    switch (current_sort) {
        case sort_name:{
            sort = [[NSSortDescriptor alloc] initWithKey:@"products_name" ascending:ascending];
            tempArr = [products sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];
            break;}
        case sort_availability:{
             NSComparator compareQantity = ^(id value1, id value2) {
                float v1 = [[value1 objectForKey:@"products_quantity"] floatValue];
                float v2 = [[value2 objectForKey:@"products_quantity"] floatValue];
                if (v1>v2) {
                    return NSOrderedAscending;
                }else{
                    return NSOrderedDescending;
                }
                return NSOrderedSame;
            };
            tempArr = [products sortedArrayUsingComparator:compareQantity];
            break;}
        case sort_price:{
            
            NSComparator comparePrice = ^(id value1, id value2) {
                float v1 = [[value1 objectForKey:@"products_price"] floatValue];
                float v2 = [[value2 objectForKey:@"products_price"] floatValue];
                if (v1>v2) {
                    return ascending?NSOrderedDescending:NSOrderedAscending;
                }else{
                    return ascending?NSOrderedAscending:NSOrderedDescending;
                }
                return NSOrderedSame;
                //return [v1 compare:v2];
            };
            
            tempArr = [products sortedArrayUsingComparator:comparePrice];
            
            break;}
        default:
            break;
    }
    
    
    [products removeAllObjects];
    [products addObjectsFromArray:tempArr];
    [self.searchDisplayController.searchResultsTableView reloadData];
}


-(IBAction)changedSort:(id)sender{
    int index = [sender tag];
    [UserDefaults setObject:[NSString stringWithFormat:@"%i",index] forKey:@"last_sort_index"];
    switch (index) {
        case 51:{//имя
            current_sort = sort_name;
            if ([[UserDefaults objectForKey:@"last_Increase_name_up"] integerValue]==1) {
                current_increase = increase_up;
            }else{
                current_increase = increase_down;
            }
            
            break;}
        case 52:{//наличие
            current_sort = sort_availability;
            break;}
        case 53:{//цена
            current_sort = sort_price;
            if ([[UserDefaults objectForKey:@"last_Increase_price_up"] integerValue]==1) {
                current_increase = increase_up;
            }else{
                current_increase = increase_down;
            }
            break;}
        default:
            break;
    }
    [self setStateSortButtons];
    [self setSortedButtonImage];
    [self sortDataTableView];
}


-(void)setSortedButtonImage{
    switch (current_sort) {
        case sort_name:{
            [button_sort_name setBackgroundImage:[UIImage imageNamed:@"sort_name_active"] forState:UIControlStateNormal];
            [button_sort_name setBackgroundImage:[UIImage imageNamed:@"sort_name_active"] forState:UIControlStateHighlighted];
            
            [button_sort_avaliable setBackgroundImage:[UIImage imageNamed:@"sort_availability"] forState:UIControlStateNormal];
            [button_sort_avaliable setBackgroundImage:[UIImage imageNamed:@"sort_availability"] forState:UIControlStateHighlighted];
            
            
            [button_sort_price setBackgroundImage:[UIImage imageNamed:@"sort_prace"] forState:UIControlStateNormal];
            [button_sort_price setBackgroundImage:[UIImage imageNamed:@"sort_prace"] forState:UIControlStateHighlighted];
            break;}
        case sort_availability:{
            [button_sort_name setBackgroundImage:[UIImage imageNamed:@"sort_name"] forState:UIControlStateNormal];
            [button_sort_avaliable setBackgroundImage:[UIImage imageNamed:@"sort_availability_active"] forState:UIControlStateNormal];
            [button_sort_price setBackgroundImage:[UIImage imageNamed:@"sort_prace"] forState:UIControlStateNormal];
            
            [button_sort_name setBackgroundImage:[UIImage imageNamed:@"sort_name"] forState:UIControlStateHighlighted];
            [button_sort_avaliable setBackgroundImage:[UIImage imageNamed:@"sort_availability_active"] forState:UIControlStateHighlighted];
            [button_sort_price setBackgroundImage:[UIImage imageNamed:@"sort_prace"] forState:UIControlStateHighlighted];
            
            break;}
        case sort_price:{
            [button_sort_name setBackgroundImage:[UIImage imageNamed:@"sort_name"] forState:UIControlStateNormal];
            [button_sort_avaliable setBackgroundImage:[UIImage imageNamed:@"sort_availability"] forState:UIControlStateNormal];
            [button_sort_price setBackgroundImage:[UIImage imageNamed:@"sort_prace_active"] forState:UIControlStateNormal];
            
            [button_sort_name setBackgroundImage:[UIImage imageNamed:@"sort_name"] forState:UIControlStateHighlighted];
            [button_sort_avaliable setBackgroundImage:[UIImage imageNamed:@"sort_availability"] forState:UIControlStateHighlighted];
            [button_sort_price setBackgroundImage:[UIImage imageNamed:@"sort_prace_active"] forState:UIControlStateHighlighted];
            break;}
        default:
            break;
    }
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [Singleton sharedMySingleton].backgroundTableView;
    
    
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc] init];
    barButton.title = @"Назад";
    self.navigationItem.backBarButtonItem = barButton;
    
    
    products = [[NSMutableArray alloc] initWithCapacity:1];
    self.searchDisplayController.searchResultsTableView.backgroundColor = [UIColor clearColor];
    
    
    
    
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    //[self.navigationItem setTitle:@"Поиск"];
    [self setNaviganionImg];
    [self setNavigationTitle];
    
    //self.searchDisplayController.searchBar.showsScopeBar = NO;
    
    for (id subview in self.searchDisplayController.searchBar.subviews )
    {
        if([subview isMemberOfClass:[UISegmentedControl class]])
        {
            UISegmentedControl *scopeBar=(UISegmentedControl *) subview;
           
            /*redSC = [[SVSegmentedControl alloc] initWithSectionTitles:[NSArray arrayWithObjects:@"Имя", @"Цена", @"Наличие", nil]];
            [redSC addTarget:self action:@selector(segmentedControlChangedValue:) forControlEvents:UIControlEventValueChanged];
            redSC.crossFadeLabelsOnDrag = YES;
            redSC.thumb.tintColor = [UIColor colorWithRed:255.0/255.0 green:1.0/255.0 blue:163.0/255.0 alpha:1];
            redSC.center = CGPointMake(self.view.frame.size.width/2, 20);
            redSC.autoresizingMask = UIViewAutoresizingFlexibleWidth;
            */
             
            
             
            self.button_sort_name = [UIButton buttonWithType:UIButtonTypeCustom];
            [self.button_sort_name setFrame:CGRectMake(67, 2, 55, 40)];
            self.button_sort_avaliable = [UIButton buttonWithType:UIButtonTypeCustom];
            [self.button_sort_avaliable setFrame:CGRectMake(122, 2, 76, 40)];
            self.button_sort_price = [UIButton buttonWithType:UIButtonTypeCustom];
            [self.button_sort_price setFrame:CGRectMake(198, 2, 55, 40)];
            
            [self.button_sort_name.titleLabel setFont:[UIFont fontWithName:@"Arial-BoldMT" size:12]];
            [self.button_sort_avaliable.titleLabel setFont:[UIFont fontWithName:@"Arial-BoldMT" size:12]];
            [self.button_sort_price.titleLabel setFont:[UIFont fontWithName:@"Arial-BoldMT" size:12]];
            
            [self.button_sort_name setTitle:@"Имя" forState:UIControlStateNormal];
            [self.button_sort_avaliable setTitle:@"Наличие" forState:UIControlStateNormal];
            [self.button_sort_price setTitle:@"Цена" forState:UIControlStateNormal];
            
            self.button_sort_name.tag = 51;
            self.button_sort_avaliable.tag = 52;
            self.button_sort_price.tag = 53;
            
            
            [self.button_sort_name addTarget:self action:@selector(changedSort:) forControlEvents:UIControlEventTouchDown];
            [self.button_sort_avaliable addTarget:self action:@selector(changedSort:) forControlEvents:UIControlEventTouchDown];
            [self.button_sort_price addTarget:self action:@selector(changedSort:) forControlEvents:UIControlEventTouchDown];
            
            /////////////////////
            
            
            self.button_sort_up = [UIButton buttonWithType:UIButtonTypeCustom];
            [self.button_sort_up setFrame:CGRectMake(14, 2, 40, 40)];
            [self.button_sort_up addTarget:self action:@selector(sortButtonPress:) forControlEvents:UIControlEventTouchUpInside];
            self.button_sort_up.tag = 1;
            
            self.button_sort_down = [UIButton buttonWithType:UIButtonTypeCustom];
            [self.button_sort_down setFrame:CGRectMake(266, 2, 40, 40)];
            [self.button_sort_down addTarget:self action:@selector(sortButtonPress:) forControlEvents:UIControlEventTouchUpInside];
            self.button_sort_down.tag = 2;
            
            [scopeBar addSubview:button_sort_down];
            [scopeBar addSubview:button_sort_up];
            [scopeBar addSubview:button_sort_avaliable];
            [scopeBar addSubview:button_sort_price];
            [scopeBar addSubview:button_sort_name];
            //[scopeBar addSubview:redSC];
            [scopeBar removeAllSegments];
            
            
            // [scopeBar setSegmentedControlStyle:UISegmentedControlStyleBar];
            // [scopeBar setTintColor: [UIColor redColor]];//you can also set RGB color here
        }
    }
    
    self.searchDisplayController.searchBar.tintColor = [UIColor clearColor];
    
    
    
    [self getCurrentSortData];
    [self setSortedButtonImage];
    [self setStateSortButtons];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [products count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"ornament_Identifier";
    ornament_cell *cell = nil;
    cell = (ornament_cell *) [self.searchDisplayController.searchResultsTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(!cell)
    {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"ornament_cell" owner:nil options:nil];
        for(id currentObject in topLevelObjects)
        {
            if([currentObject isKindOfClass:[ornament_cell class]])
            {
                cell = (ornament_cell *)currentObject;
                break;
            }
        }
    }
    
    
    cell.description.text = [[products objectAtIndex:indexPath.row] objectForKey:@"products_short_description"];
    cell.name_product.text = [[products objectAtIndex:indexPath.row] objectForKey:@"products_name"];
    
    cell.price.text = [NSString stringWithFormat:@"%i",[[[products objectAtIndex:indexPath.row] objectForKey:@"products_price"] integerValue]];
    
    [cell.small_image setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://moda.viva-viva.ru/images/product_images/info_images/%@",[[products objectAtIndex:indexPath.row] objectForKey:@"products_image"]]]
                     placeholderImage:[UIImage imageNamed:@"placeholderImage"]];
    
    
    cell.small_image.layer.masksToBounds = YES;
    [cell.small_image.layer setCornerRadius:8];
    
    
    if ([[[products objectAtIndex:indexPath.row] objectForKey:@"products_quantity"] integerValue]<=0) {
        cell.sold_image.hidden = NO;
    }else{
        cell.sold_image.hidden = YES;
    }
    
    UIView *selected_view = [[UIView alloc] init];
    selected_view.backgroundColor = [UIColor clearColor];
    cell.selectedBackgroundView = selected_view;
    
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.searchDisplayController.searchResultsTableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (!detail_product) {
        detail_product = [[DetailProduct alloc] initWithNibName:@"DetailProduct" bundle:nil];
    }
    
    detail_product.id_product = [[[products objectAtIndex:indexPath.row] objectForKey:@"products_id"] integerValue];
    detail_product.name_product = [[products objectAtIndex:indexPath.row] objectForKey:@"products_name"];
    detail_product.name_image = [[products objectAtIndex:indexPath.row] objectForKey:@"products_image"];
    detail_product.price = [[[products objectAtIndex:indexPath.row] objectForKey:@"products_price"]integerValue];
    
    detail_product.short_description = [[products objectAtIndex:indexPath.row] objectForKey:@"products_short_description"];
    
    detail_product.needReload = YES;
    detail_product.fromSearch = YES;
    [self.navigationController pushViewController:detail_product animated:YES];
}



- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 99;
}




- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    
    if(!controller.isActive){
        controller.searchResultsTableView.hidden = YES;
        return NO;
    }
    controller.searchResultsTableView.hidden = YES;
    return YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar*)searchBar
{
    [self.searchDisplayController.searchResultsTableView setBackgroundView:nil];
    [self.searchDisplayController.searchResultsTableView setBackgroundView:[[UIView alloc] init]];
    [self.searchDisplayController.searchResultsTableView setSeparatorColor:[UIColor clearColor]];
    [self.searchDisplayController.searchResultsTableView setSeparatorStyle:UITableViewCellSelectionStyleNone];
    
    
    
    
    [products removeAllObjects];
    [self parseData:searchBar.text];
    //self.searchDisplayController.searchResultsTableView.hidden = YES;
   // [self.searchDisplayController.searchResultsTableView reloadData];
    
    [self.searchDisplayController.searchResultsTableView setBackgroundColor:[Singleton sharedMySingleton].backgroundTableView];
    //self.view.backgroundColor = [Singleton sharedMySingleton].backgroundTableView;
}




#pragma mark Dejal activity

- (void)displayActivityView
{
    //[self removeActivityView];
    
    if ([DejalActivityView isActive]) {
        return;
    }
    
    UIView *viewToUse = self.tabBarController.tabBar.superview;
    [DejalBezelActivityView activityViewForView:viewToUse];
    [DejalActivityView currentActivityView].showNetworkActivityIndicator = YES;
    [DejalActivityView currentActivityView].activityLabel.text = @"Синхронизация";
}

- (void)removeActivityView;
{
    [DejalBezelActivityView removeViewAnimated:YES];
    [[self class] cancelPreviousPerformRequestsWithTarget:self];
}

#pragma mark



-(void)parseData:(NSString*)searchText{
    NSURL* url = [NSURL URLWithString:[[NSString stringWithFormat:@"http://moda.viva-viva.ru/mobile/get_product_keyword.php?keyword=%@",searchText]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
        
    //NSLog(@"url = %@",url);
    
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
    [self displayActivityView];
    if (connection) {
        self.infoData = [NSMutableData data];
    }
}




- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    //[self removeActivityView];
    [self showNoInternetAlert];
}



- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [infoData appendData:data];
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{
    //NSString *result = [[NSString alloc] initWithData:infoData encoding:NSUTF8StringEncoding];
    //NSLog(@"result = %@", result);
    [self parseJSON:infoData];
    // [self removeActivityView];
    
}


#pragma mark parse JSON result

-(void)parseJSON:(NSData*)data{
    NSDictionary *temtData;
    NSString *tempSliteText=@"";
    NSError* error;
    NSDictionary* json = [NSJSONSerialization
                          
                          JSONObjectWithData:data
                          
                          options:kNilOptions
                          
                          error:&error];
    
    NSString* requestResultAutorization = [json objectForKey:@"success"];
    
    NSArray * array = [json objectForKey:@"message"];
    
    if ([requestResultAutorization integerValue]==1) {
      //  [SQLiteAccess deleteWithSQL:[NSString stringWithFormat:@"DELETE FROM ProductData WHERE id_categoria=%i",self.id_categories]];
        
        for (int i=0; i< [array count];i++) {
            
            NSString *prod_img = [[array objectAtIndex:i] objectForKey:@"products_image"];
            NSString *prod_name = [[array objectAtIndex:i] objectForKey:@"products_name"];
            NSString *prod_id = [[array objectAtIndex:i] objectForKey:@"products_id"];
            NSString *prod_price = [[array objectAtIndex:i] objectForKey:@"products_price"];
            NSString *prod_short_descript = [[array objectAtIndex:i] objectForKey:@"products_short_description"];
            NSString *products_quantity = [[array objectAtIndex:i] objectForKey:@"products_quantity"];
            
            
            
            temtData = [NSDictionary dictionaryWithObjects:@[
                        prod_img,
                        prod_name,
                        prod_id,
                        prod_price,
                        [NSString stringWithFormat:@"%@",[[array objectAtIndex:i] objectForKey:@"products_last_modified"]],
                        prod_short_descript,
                        products_quantity
                        ]
                                                   forKeys:@[
                        @"products_image",
                        @"products_name",
                        @"products_id",
                        @"products_price",
                        @"products_last_modified",
                        @"products_short_description",
                        @"products_quantity"
                        ]
                        ];
            [products addObject:temtData];
            
            
            //tempSliteText = [NSString stringWithFormat:@"%@;INSERT INTO ProductData(id_categoria,id_product,name_product,short_description,price,small_image,search_key) VALUES(-1,%i,'%@','%@','%@','%@','%@')",tempSliteText,[prod_id integerValue],prod_name,prod_short_descript,prod_price,prod_img,self.key_podbor];
                
         }
        //[SQLiteAccess insertWithSQL:tempSliteText];
        
    }else{
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Уведомление" message:@"Ошибка синхронизации" delegate:nil cancelButtonTitle:@"Закрыть" otherButtonTitles:nil];
        [alert show];
    }
    
    
    
    self.searchDisplayController.searchResultsTableView.hidden = NO;
    [self.searchDisplayController.searchResultsTableView reloadData];
    [self removeActivityView];
    
    
    
    
    
    
    
    
    //[self sortDataTableView];
//    [self getCurrentSortData];/// automatic run sort and reload tableview
  //  [self removeActivityView];
    
}







- (void)showNoInternetAlert
{
    BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Ошибка Internet соединения" message:@"Для работы с магазином необходимо подключение к сети Internet. Пожалуйста, проверте подключение к сети и повторите попытку."];
    [alert setCancelButtonWithTitle:@"Закрыть" block:^{
        //[self runSQl];
        //[self.tableView reloadData];
        [self removeActivityView];
    }];
    //[alert setDestructiveButtonWithTitle:@"Повторить" block:nil];
    [alert addButtonWithTitle:@"Повторить " block:^{
        //[self displayActivityView];
        [self performSelector:@selector(parseData:) withObject:self.searchDisplayController.searchBar.text afterDelay:1.0];
    }];
    [alert show];
}







-(BOOL)InternetConnection{
    internetReach = [Reachability reachabilityForInternetConnection];
    NetworkStatus netStatus = [internetReach currentReachabilityStatus];
    if (netStatus == ReachableViaWiFi || netStatus == ReachableViaWWAN) {
        return YES;
    }else{
        return NO;
    }
    
}


-(void)setNaviganionImg{
    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) {
        UIImage *image = [UIImage imageNamed:@"navigation_bg"];
        [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
        
    }
}

-(void)setNavigationTitle{
    UILabel *lblTitle = [[UILabel alloc] init];
    lblTitle.text = @"Поиск";
    lblTitle.backgroundColor = [UIColor clearColor];
    lblTitle.textColor = [UIColor colorWithRed:242.0/255.0 green:240.0/255.0 blue:234.0/255.0 alpha:1];
    
    lblTitle.font = [UIFont fontWithName:@"American Retro" size:27.0];
    [lblTitle sizeToFit];
    
    self.navigationItem.titleView = lblTitle;
}

@end
